##
## Initial 2020-01-07
##

# https://ucdp.uu.se/downloads/olddw.html
#Scroll down to UCDP Georeferenced Event Dataset (GED) Global version.
#Click on the R tab.

output_version <- '2021-01-07'
url <- 'https://ucdp.uu.se/downloads/ged/ged201-RData.zip'

destfile <- file.path(wkdir,'local','tab_data',basename(url))
xfun::dir_create(dirname(destfile))

# Download the file
httr::GET(url, write_disk(destfile, overwrite = TRUE))

# Unzip the downloaded file
setwd(dirname(destfile))
unzip(destfile)

load(file.path(dirname(destfile),'ged201.RData'))

# subset lake chad countries
lkcctr <- c('Cameroon','Chad','Niger','Nigeria')
ucdp_df <- subset(ged201,country %in% lkcctr)
dim(ucdp_df)

# convert to points
ucdp_sf = st_as_sf(ucdp_df, coords = c("longitude", "latitude"), 
                 crs = 4326, agr = "constant")

# ntl_adm0_x_01d
ntl.zones <- read_sf(dsn=paste0(wkdir,'/local/gis_data/003_boundaries/fishnet'),layer='fishnet_lake_chad_ntl_adm0_x_d01')
ntl.zones <- subset(ntl.zones,select=c(OBJECTID,GID_0))

setwd(wkdir)

# join points to objectid
ucdp_objectid_sf <- st_join(ucdp_sf,ntl.zones,join=st_nearest_feature)

# output for stata labels
out <- as.data.frame(st_drop_geometry(ucdp_objectid_sf))
summary(out)
save.dta13(out, 
           paste0(wkdir,"/proc_data/UCDP",output_version,".dta"),
           convert.factors = FALSE,convert.underscore=TRUE)
